import webapp2
from google.appengine.api import users
from google.appengine.ext import db
import json
import calendar

class Note(db.Model):
  content = db.TextProperty(required=True)
  user = db.UserProperty(required=True)
  created_at = db.DateTimeProperty(auto_now_add=True)
  updated_at = db.DateTimeProperty(auto_now=True)

class NewNotePage(webapp2.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      return self.redirect(users.create_login_url("/notes"))

    content = self.request.get('content')
    new_note = Note(content = content, user = user)
    new_note.put()
    self.redirect('/notes')

class NotePage(webapp2.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      return self.redirect(users.create_login_url("/notes"))

    notes = Note.all().filter('user =', user)
    data = []

    self.response.headers.add_header("Content-Type", "application/json")
    for note in notes:
      data.append({
          'content': note.content
        , 'updated': calendar.timegm(note.updated_at.utctimetuple())
        , 'created': calendar.timegm(note.created_at.utctimetuple())
      })
    
    self.response.out.write(json.dumps(data))



app = webapp2.WSGIApplication([
                              ('^/notes/new$', NewNotePage),
                              ('^/notes$', NotePage),
                              ],
                              debug=True)

